<?php
// 应用公共文件
use think\facade\Cache;

if (!function_exists('headerToken')) {
    function headerToken()
    {

        return \think\facade\Request::header('token');

    }
}

if (!function_exists('generate_salt')) {
    function generate_salt()
    {
        return uniqid();
    }
}

if (!function_exists('password')) {
    function password($pwd, $salt)
    {
        return md5(md5($pwd) . $salt);
    }
}

if (!function_exists('generate_token')) {
    function generate_token($user, $roles)
    {

        $data = [
            'id' => $user->id,
            'role' => $roles ? json_encode($roles) : '',
            'phone' => $user->phone,
            'douyin' => $user->douyin,
            'time' => time(),
            'iat' => time(),
            'exp' => time() + 2592000,
        ];

        return \Firebase\JWT\JWT::encode($data, config('app.key'), 'HS256');

    }
}

if (!function_exists('decode_token')) {

    function decode_token($token)
    {

        $result = null;
        try {
            $result = \Firebase\JWT\JWT::decode($token, config('app.key'), ['HS256']);
        } catch (\Firebase\JWT\SignatureInvalidException $e) {
            echo json_encode(['code' => 401, 'msg' => '签名不正确']);
            exit;
        } catch (\Firebase\JWT\BeforeValidException $e) {
            echo json_encode(['code' => 401, 'msg' => '签名在某个时间点之后才能用']);
            exit;
        } catch (\Firebase\JWT\ExpiredException $e) {//过期
            echo json_encode(['code' => 401, 'msg' => '请登录']);
            exit;
        } catch (\Exception $e) {
            echo json_encode(['code' => -1, 'msg' => 'token格式不正确']);
            exit;
        }
        return $result;
    }

}

if (!function_exists('cache_get')) {
    function cache_get($name)
    {
        return \think\facade\Cache::store('redis')->get($name);
    }
}

if (!function_exists('cache_set')) {
    function cache_set($key, $value, $ttl = 300)
    {
        return \think\facade\Cache::store('redis')->set($key, $value, $ttl);
    }
}

if (!function_exists('getUid')) {
    function getUid($type = 1)
    {
        $token = headerToken();
        if (!$token) echo json(['code' => 401, 'fail']);
        $user = decode_token($token);
        if ($type == 1) {
            return $user->id;
        } else if ($type == 2) {
            return $user->phone;
        }
    }
}

if (!function_exists('getChild')) {
    function getChild($data, $id = 0, $field = 'pid')
    {
        $child = [];

        foreach ($data as $key => $datum) {
            if ($datum[$field] == $id) {
                $child[$datum['cid']] = $datum;
                unset($data[$key]);
                $child[$datum['cid']]['child'] = getChild($data, $datum['cid'], $field);
            }
        }
        return $child;
    }
}

if (!function_exists('filterEmoji')) {
    function filterEmoji($str)
    {
        $str = preg_replace_callback('/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }
}

if (!function_exists('checkBindPhone')) {
    function checkBindPhone($token)
    {
        $user = decode_token($token);
        $phone = \app\model\User::where(['id' => $user->id])->value('phone');
        if ($phone == '') {
            echo json_encode(['code' => 406, 'msg' => '未绑定手机号']);
            exit;
        }
        return true;
    }
}

if (!function_exists('generatie_aid')) {
    function generatie_aid()
    {
        return mt_rand(1111, 9999) . mt_rand(1111, 9999) . mt_rand(1111, 9999) . mt_rand(1111, 9999);
    }
}

if (!function_exists('randFloat')) {
    function randFloat($min = 0, $max = 1)
    {
        return round($min + mt_rand() / mt_getrandmax() * ($max - $min), 1);
    }
}

if (!function_exists('isMobile')) {
    function isMobile($mobile)
    {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
    }
}

if (!function_exists('checkCode')) {
    function checkCode($phone, $type, $code)
    {
        $key = $phone . '_' . $type;
        $cache_code = cache_get($key);
        if (!$cache_code || ($code != $cache_code)) {
            return false;
        }
        Cache::store('redis')->delete($key);
        return true;
    }
}

if (!function_exists('formatTime')) {
    function formatTime($time, $end)
    {
        $time = (int)substr($time, 0, 10);
        $int = $end - $time;
        $str = '';
        $hour = 0;
        $min = 0;
        if ($int < 60) {
            $str = sprintf('%d分钟', floor($int / 60));
        } else if ($int < 86400) {
            $hour = floor($int / 3600);
            $min = ($int - ($hour * 3600)) / 60;
            $str = sprintf('%d小时 %d分钟', $hour, $min);
        }

        return $str;
    }
}

if (!function_exists('dlfile')) {
    function dlfile($file_url, $save_to)
    {
        $content = file_get_contents($file_url);
        file_put_contents($save_to, $content);
    }
}

if(!function_exists('cut_str')){
    function cut_str($string, $sublen, $start = 0, $code = 'UTF-8') {
        if ($code == 'UTF-8') {
            $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
            preg_match_all($pa, $string, $t_string);
            if (count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen)) . "...";
            return join('', array_slice($t_string[0], $start, $sublen));
        } else {
            $start = $start * 2;
            $sublen = $sublen * 2;
            $strlen = strlen($string);
            $tmpstr = '';
            for ($i = 0; $i < $strlen; $i++) {
                if ($i >= $start && $i < ($start + $sublen)) {
                    if (ord(substr($string, $i, 1)) > 129) {
                        $tmpstr.= substr($string, $i, 2);
                    } else {
                        $tmpstr.= substr($string, $i, 1);
                    }
                }
                if (ord(substr($string, $i, 1)) > 129) $i++;
            }
            if (strlen($tmpstr) < $strlen) $tmpstr.= "";
            return $tmpstr;
        }
    }
}